package com.yimaxiaoerlang.http;

import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpClientHelper {
    private static final Long TIMEOUT = 5000L;
    private OkHttpClient okHttpClient;
    private Interceptor interceptor;
    public OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .addInterceptor(interceptor!=null?interceptor: (Interceptor) chain -> {
                        Request original = chain.request();

                        return chain.proceed(
                                original.newBuilder()
                                        .header("Content-Type", "application/json")
                                        .method(original.method(), original.body())
                                        .build()
                        );
                    })
                    .build();
        }
        return okHttpClient;
    }
    public void addInterceptor(Interceptor interceptor){
        this.interceptor=interceptor;
    }
    private static OkHttpClientHelper clientHelper;

    public static OkHttpClientHelper getInstance() {
        if (clientHelper==null){
            synchronized(OkHttpClientHelper.class){
                if (clientHelper==null){
                    clientHelper=new OkHttpClientHelper();
                }
            }
        }
        return clientHelper;
    }
}
